package xin.nick.persistence.core.builder;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import xin.nick.persistence.core.Resources;
import xin.nick.persistence.core.entity.Configuration;
import xin.nick.persistence.core.session.DefaultSqlSessionFactory;
import xin.nick.persistence.core.session.SqlSessionFactory;

import java.beans.PropertyVetoException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author Nick
 * @date 2021/5/24
 * @description
 */
public class SqlSessionFactoryBuilderByProperties {

    public static SqlSessionFactory build(Properties properties) throws DocumentException, PropertyVetoException, ClassNotFoundException, IOException {

        Configuration configuration = new Configuration();

        // 创建数据源
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("datasource.driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("dataSource.jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("datasource.username"));
        comboPooledDataSource.setPassword(properties.getProperty("datasource.password"));
        configuration.setDataSource(comboPooledDataSource);

        // 解析Mapper
        String mapperParentPath = properties.getProperty("mapper.resource.package");
        String projectPath = properties.getProperty("classPath");
        String fullMapperPath = projectPath + mapperParentPath;
        File mapperPathFile = new File(fullMapperPath);
        for (File file : mapperPathFile.listFiles()) {
            String realPath = mapperParentPath + File.separator + file.getName();
            InputStream resourceAsSteam = Resources.getResourceAsStream(realPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsSteam);
        }

        // 创建SqlSessionFactory,并设置Configuration
        SqlSessionFactory sqlSessionFactory = new DefaultSqlSessionFactory(configuration);

        return sqlSessionFactory;
    }

}
